package org.future.dev.file;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;

/**
 *@date 2010-3-25 下午09:38:40
 *@author dycc
 *@file org.future.dev.file.FileDownload.java
 */
public class FileDownload {
	/**
	 * 下载文件
	 * @param req
	 * @param resp
	 * @param filePath
	 * @param saveName
	 */
	public static void download(ServletRequest req,ServletResponse resp,
			String filePath,String saveName)
		throws IOException{
		download(req,resp,filePath,saveName,"application/octet-stream","attachment");
	}
	/**
	 * 下载文件
	 * @param req
	 * @param resp
	 * @param filePath
	 * @param saveName
	 * @param contentType  |
	 * @param mode         | attachment or inline
	 */
	public static void download(ServletRequest req,ServletResponse resp,
			String filePath,String saveName,
			String contentType,String mode)throws IOException{
		resp.reset();                           // 清空之前输出流中的内容
		OutputStream out = resp.getOutputStream();
		// 
		String fileName = encodeFileName(req, saveName);
		// set header
		HttpServletResponse response = (HttpServletResponse)resp;
		response.setContentType(contentType);
		response.setHeader("Content-Disposition", mode + ";filename=\"" + fileName + "\"");
		response.setHeader("Connection", "close");
		// print file content
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(filePath));
		byte[] data = new byte[1024];
		int len = -1;
		while((len = in.read(data,0,data.length)) > 0){
			out.write(data,0,len);
			out.flush();
		}
		in.close();
		out.close();
	}
	/**
	 * 对文件名编码,避免浏览器保存时出现文件名乱码
	 * @param req
	 * @param fileName
	 * @return
	 */
	public static String encodeFileName(ServletRequest req,String fileName){
		String name = fileName;
		String browser = ((HttpServletRequest)req).getHeader("USER-AGENT");
		if(browser == null){
			return name;
		}
		try{
			if(browser.indexOf("MSIE") > -1){
				// ie
				name = URLEncoder.encode(fileName, "UTF-8");
				// 处理文件名中的空格
				name = name.replace("+", "%20");
			} else if(browser.indexOf("Mozilla") > -1){
				// firefox
				name = "=?UTF-8?B?";
				name += new BASE64Encoder().encode(fileName.getBytes());
				name += "?=";
			} else{
				// other
				name = fileName;
			}
		} catch(Exception e){
			name = fileName;
		}	
		return name;
	}
}
